package cn.tedu.bonfire.front.content.dao.search.impl;

import cn.tedu.bonfire.common.pojo.po.ArticleSearchPO;
import cn.tedu.bonfire.common.pojo.vo.PageData;
import cn.tedu.bonfire.front.content.dao.search.IArticleSearchRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class ArticleSearchRepositoryImpl implements IArticleSearchRepository {

    @Autowired
    private ArticleElasticsearchRepository elasticsearchRepository;

    @Override
    public PageData<ArticleSearchPO> search(String keyword, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(--pageNum, pageSize);
        SearchPage<ArticleSearchPO> searchPage = elasticsearchRepository.search(keyword, pageable);
        PageData<ArticleSearchPO> articleSearchPageData = new PageData<>();
        SearchHits<ArticleSearchPO> searchHits = searchPage.getSearchHits();

        long totalHits = searchHits.getTotalHits();
        int number = searchPage.getNumber();
        int size = searchPage.getSize();
        int totalPages = searchPage.getTotalPages();

        articleSearchPageData.setMaxPage(totalPages);
        articleSearchPageData.setCurrentPage(number + 1);
        articleSearchPageData.setPageSize(size);
        articleSearchPageData.setTotal(totalHits);

        List<ArticleSearchPO> articleList = new ArrayList<>();
        for (SearchHit<ArticleSearchPO> searchHit: searchHits) {
            ArticleSearchPO articleSearchPO = searchHit.getContent();
            List<String> highlightField = searchHit.getHighlightField("title");
            if (highlightField.size()>0){
                articleSearchPO.setTitle(highlightField.get(0));
            }
            articleList.add(articleSearchPO);

        }
        articleSearchPageData.setList(articleList);
        return articleSearchPageData;
    }
}
